# uncompyle6 version 2.11.5
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.9 (default, Sep 17 2016, 20:26:04) 
# [GCC 4.9.2]
# Embedded file name: D:\project\inleader_frist_client\print_client\core\rpc_thread.py
# Compiled at: 2014-01-11 03:41:58
import commands
import socket
from printer import DefaultPrinter
import threading
import time
from utils.http import UrllibHttpUtils
from setting import setting, Vfs
from PyQt5.QtCore import Qt, QObject, pyqtSignal
import UI_thread
NET_ERROR = False

class RpcThread(QObject, threading.Thread):

    def __init__(self, uiMain):
        threading.Thread.__init__(self)
        QObject.__init__(self)
        self.uiMain = uiMain
        self.printCode = None
        self.isQuit = threading.Event()
        self.isQuit.clear()
        self.refreshPrintCode()
        return

    def stop(self):
        self.isQuit.set()
        self.join()

    def refreshPrintCode(self, force=False):
        if force or self.printCode is None or self.printCode == '':
            response = UrllibHttpUtils.callRpc('get_code', {'macaddress': setting.getMac()})
            if response is None:
                self.uiMain.onGetVerifyCodeFailure()
                setting.logger.debug('get verify code failure')
                return
            if response['code'] == '#####':
                self.printCode = response['code']
                setting.logger.debug('get special code ######')
                self.uiMain.onGetSpecialCode()
                return
            self.printCode = response['code']
            self.uiMain.onRefreshPrintCode(self.printCode)
        return

    def _execute(self):
        if not self.checkNetworkEnable():
            self.uiMain.onCheckNetWorkFailureSignal()
            time.sleep(5)
            return
        else:
            response = UrllibHttpUtils.callRpc('get_print_task', {'print_code': unicode(self.printCode),'macaddress': setting.getMac()
               })
            if response is None:
                if self.printCode == '#####':
                    self.uiMain.onGetSpecialCode()
                elif self.printCode is None:
                    self.refreshPrintCode(True)
                else:
                    self.uiMain.onRefreshPrintCode(self.printCode)
                if UI_thread.IS_REFRESH:
                    self.uiMain.onRefreshUI()
                    UI_thread.IS_REFRESH = False
                time.sleep(3)
                return
            imageList = response['images']
            if len(imageList) != 0:
                for imageFile in imageList:
                    self.uiMain.onDownloadSuccess()
                    tmpImage = UrllibHttpUtils.downloadPoto(imageFile)
                    if tmpImage is None:
                        self.uiMain.onDownloadFailuer()
                        UrllibHttpUtils.callRpc('update_print_task', {'print_code': unicode(self.printCode),'macaddress': setting.getMac()
                           })
                        self.refreshPrintCode(True)
                        time.sleep(3)
                        return
                    self.refreshPrintCode(True)
                    while not self.printPoto(tmpImage):
                        self.cancelAllJobs()
                        self.uiMain.onUpdatePrintPotoFailure()
                        if not self.checkPrintEnable():
                            self.enablePrint()
                        time.sleep(30)

                    UrllibHttpUtils.callRpc('complete_print_task', {'print_code': self.printCode,'macaddress': setting.getMac()
                       })
                    Vfs.deleteTempFile(tmpImage)

            else:
                time.sleep(3)
                setting.logger.debug('thread sleep')
            return

    def cancelAllJobs(self):
        cmd = '/usr/bin/cancel -a'
        result = commands.getoutput(cmd)
        pos = result.find('failed')
        if pos != -1:
            return False
        else:
            return True

    def enablePrint(self):
        cmd = "/usr/sbin/cupsenable 'EPSON_Stylus_Photo_R230'"
        result = commands.getoutput(cmd)
        pos = result.find('failed')
        if pos != -1:
            return False
        else:
            return True

    def checkPrintEnable(self):
        time.sleep(3)
        cmd = 'lpstat -p'
        result = commands.getoutput(cmd)
        setting.logger.debug(cmd)
        pos = result.find('enabled')
        if pos != -1:
            return True
        else:
            return False

    def printPoto(self, printImage):
        defualtPrinter = DefaultPrinter()
        jobId = defualtPrinter.printFile(printImage)
        if jobId < 0:
            setting.logger('\xe6\x8f\x90\xe4\xba\xa4\xe6\x89\x93\xe5\x8d\xb0\xe4\xbb\xbb\xe5\x8a\xa1\xe5\xa4\xb1\xe8\xb4\xa5')
            return False
        time.sleep(10)
        self.uiMain.onUpdatePrintPoto(printImage)
        start_time = int(time.time())
        time_out = 120
        while not defualtPrinter.isComplete(jobId):
            progress = defualtPrinter.progress(jobId)
            time.sleep(3)
            self.uiMain.onUpdatePrintProgress(progress)
            end_time = int(time.time())
            spend_time = end_time - start_time
            if spend_time > time_out:
                setting.logger.debug('Printer is timeout error!!!!')
                self.uiMain.onUpdatePrintProgress(0)
                return False

        self.uiMain.onUpdatePrintProgress(100)
        self.uiMain.onUpdatePrintPoto('')
        return True

    def checkNetworkEnable(self):
        old = socket.getdefaulttimeout()
        socket.setdefaulttimeout(60)
        test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            try:
                test_sock.connect(('www.baidu.com', 80))
            except socket.error as e:
                print '\xe7\xbd\x91\xe7\xbb\x9c\xe8\xbf\x9e\xe6\x8e\xa5\xe4\xb8\x8d\xe4\xb8\x8a'
            except socket.timeout as e:
                print '\xe7\xbd\x91\xe7\xbb\x9c\xe8\xbf\x9e\xe6\x8e\xa5\xe4\xb8\x8d\xe4\xb8\x8a'

        finally:
            test_sock.close()
            socket.setdefaulttimeout(old)
            return self.checkNetworkEnable1()

    def checkNetworkEnable1(self):
        old = socket.getdefaulttimeout()
        socket.setdefaulttimeout(60)
        test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            try:
                test_sock.connect(('www.baidu.com', 80))
            except socket.error as e:
                print '\xe7\xbd\x91\xe7\xbb\x9c\xe8\xbf\x9e\xe6\x8e\xa5\xe4\xb8\x8d\xe4\xb8\x8a1'
            except socket.timeout as e:
                print '\xe7\xbd\x91\xe7\xbb\x9c\xe8\xbf\x9e\xe6\x8e\xa5\xe4\xb8\x8d\xe4\xb8\x8a1'

        finally:
            test_sock.close()
            socket.setdefaulttimeout(old)
            return self.checkNetworkEnable2()

    def checkNetworkEnable2(self):
        global NET_ERROR
        old = socket.getdefaulttimeout()
        socket.setdefaulttimeout(60)
        test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            try:
                test_sock.connect(('www.baidu.com', 80))
            except socket.error as e:
                print '\xe7\xbd\x91\xe7\xbb\x9c\xe8\xbf\x9e\xe6\x8e\xa5\xe4\xb8\x8d\xe4\xb8\x8a2'
                NET_ERROR = False
                return False
            except socket.timeout as e:
                print '\xe7\xbd\x91\xe7\xbb\x9c\xe8\xbf\x9e\xe6\x8e\xa5\xe4\xb8\x8d\xe4\xb8\x8a2'
                NET_ERROR = False
                return False

        finally:
            test_sock.close()
            socket.setdefaulttimeout(old)

        NET_ERROR = True
        if NET_ERROR:
            self.refreshPrintCode(True)
        return True

    def run(self):
        while not self.isQuit.isSet():
            try:
                self._execute()
            except:
                setting.logger.exception('error')